﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FormView.UI.ChoiceView
{
	public class MultiChoiceWindow : FormWindowBase
	{
		private HashSet<int> mSelectedIdx = new HashSet<int>();

		public MultiChoiceWindow(string @namespace) : base(@namespace)
		{
			EnableFooterBar();
		}

		public void LoadView(string[] items, int[] defaultIndexs)
		{
			if (items == null)
			{
				throw new ArgumentException("MultiChoice组件选项不可为空");
			}

			var idxSet = defaultIndexs == null ? new HashSet<int>() : new HashSet<int>(defaultIndexs);

			for (var i = 0; i < items.Length; i++)
			{
				string item = items[i];
				Grid grid = new Grid()
				{
					Background = new SolidColorBrush(ParseColorStr("#99000000")),
				};
				CheckBox cbx = new CheckBox()
				{
					Style = Resources["CheckboxStyle"] as Style,
					Content = item,
					IsChecked = idxSet.Contains(i),
					Foreground = DefaultForeColor,
					Background = new SolidColorBrush(Colors.Transparent),
					FontSize = 14,
					Padding = new Thickness(10, 5, 10, 5),
					VerticalAlignment = VerticalAlignment.Center,
					VerticalContentAlignment = VerticalAlignment.Center,
					BorderThickness = new Thickness(0, 1, 0, 0),
					Tag = i
				};
				if (idxSet.Contains(i))
				{
					mSelectedIdx.Add(i);
				}
				cbx.Click += (sender, args) =>
				{
					bool res = cbx.IsChecked == null ? false : (bool)cbx.IsChecked;
					if (res)
					{
						mSelectedIdx.Add((int) cbx.Tag);
					}
					else
					{
						mSelectedIdx.Remove((int) cbx.Tag);
					}
				};
				grid.Children.Add(cbx);
				AddControl(grid);
			}
		}

		protected override FormResult GetFormResult()
		{
			List<int> selectResults = mSelectedIdx.ToList();
			selectResults.Sort();
			return new FormResult(selectResults);
		}

		protected override FormResult OnUserCloseWinGetResult()
		{
			return new FormResult(null);
		}
	}
}
